------------------------------------------------------------------------------------------------------------------------------------------------
-- -- tasks base lib
-- local function language_change_say(theNPC)
--     theNPC.CHAT_TABLE = {}
--     if theNPC.npc_base_lib:Get_Language() == "ch" then
--         theNPC.CHAT_TABLE.it_is_for_you = "这个给你"
--     else
--         theNPC.CHAT_TABLE.it_is_for_you = "This is for you"    
--     end
-- end

local function language_change_say(theNPC)
    theNPC.CHAT_TABLE = {}
    pcall(function()
        -- theNPC.npc_base_lib:Get_Language() == "ch"
        theNPC.CHAT_TABLE = TUNING.NPC_CHAT_TABLE[ theNPC.npc_base_lib:Get_Language() ] ["npc_event_deal_with_bat"] or {}
    end)
end

-------------------------------------------------------------------------------------------------------------------------------------------------
local function talk_fn(theNPC,_table)
    if _table and _table.talk then
        theNPC:DoTaskInTime(0.3,function()

            -- theNPC.npc_base_lib:Say(_table.talk)     
            if theNPC.____ask_item ~= "reviver" then
                theNPC.____ask_item = "reviver"
            else
                theNPC.____ask_item = "amulet"
            end

            theNPC.npc_base_lib:Show_Chat_Bubble({
                image = theNPC.____ask_item,
                num = 1,
                height = 4.3
            })


        end)
    end
end

local function Time_Out_Leave(inst)
    local theNPC = inst.entity:GetParent()
    local time = theNPC.npc_base_lib:Get_Time_Out()
    if time then
        inst:DoTaskInTime(time,function()
            inst:Remove()
            theNPC:AddDebuff("npc_event_leave","npc_event_leave")
            theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.too_late)
            print("Warning : npc time out and leave")
            theNPC:AddTag("INLIMBO")
        end)
    end
end

local function Chat_Bubble_Fn(theNPC)
    theNPC.npc_base_lib:Show_Chat_Bubble({
        image = "reviver",
        num = theNPC.__item_ask_num - theNPC.npc_everything_data:Add("deal",0),
        height = 4.3
    })
end

local function Item_Get_Event_Init(theNPC)
    -- theNPC:ListenForEvent("itemget",function(theNPC,_table)  ----    进入删除的话，不会触发这个 event
    --     print("itemget")

    --     if _table and _table.item then            
    --         local item = _table.item
    --         if item.prefab == "reviver" then
    --             local ret = theNPC.npc_everything_data:Add("deal",1)
    --             if ret == 3 then
    --                 theNPC.event_step = 1
    --                 theNPC.npc_base_lib:Hide_Chat_Bubble()
    --             else
    --                 theNPC.__item_ask_num = theNPC.__item_ask_num - ret
    --             end
    --         end
    --     end
    -- end)
 
    -------------------------------------------------------------------------
    local function ShouldAcceptItem(inst, item)
        if item and item.prefab == "reviver" then
            return true
        end
    end
    local function OnGetItem(inst, giver, item)
        print("OnGetItem ,Giver :",giver,item)
        -- theNPC:PushEvent()
        if item.prefab == "reviver" then
            local ret = theNPC.npc_everything_data:Add("deal",1)

           if  theNPC.__item_ask_num - ret == 0 then
                theNPC.event_step = 1
                theNPC.npc_base_lib:Hide_Chat_Bubble()
           else
                Chat_Bubble_Fn(theNPC)
           end

        end
    end
    local function abletoaccepttest(inst,item,giver)
        if item and item.prefab == "reviver" then
            return true
        end
    end
    theNPC.components.trader:SetAcceptTest(ShouldAcceptItem)
    theNPC.components.trader.onaccept = OnGetItem
    theNPC.components.trader.deleteitemonaccept = true
    theNPC.components.trader:SetAbleToAcceptTest(abletoaccepttest)
    -------------------------------------------------------------------------
    -- -- 搜索附近地上的
    -- theNPC.find_around_item_task =   theNPC:DoPeriodicTask(0.3,function()
    --     if theNPC.event_step ~= nil then
    --         if theNPC.find_around_item_task then
    --             theNPC.find_around_item_task:Cancel()
    --             theNPC.find_around_item_task = nil
    --         end
    --         return
    --     end
    --     local canthavetags = { "companion","isdead","player","INLIMBO", "notarget", "noattack", "flight", "invisible", "playerghost" ,"chester","hutch","wall","structure"}
    --     local x,y,z = theNPC.Transform:GetWorldPosition()
    --     local ents = TheSim:FindEntities(x, 0, z, 3, {"reviver"}, canthavetags, nil)
    --     if #ents > 0 then
    --         for k, item in pairs(ents) do
    --             if item and item:IsValid() and item.prefab == "reviver" and
    --                 item.components.inventoryitem and item.components.inventoryitem.owner == nil
    --             then
    --                 OnGetItem(theNPC,nil,item)
    --                 item:Remove()
    --             end
    --         end 
    --     end
    -- end)
    -------------------------------------------------------------------------

end


local function GiveItem(theNPC,flag)
    if flag ~= true then
        theNPC.components.container:DropEverything()
        theNPC.components.container:DropEverythingWithTag("npc_event_deal_with_bat.item")
        return
    end
        
    local item_cmd = {
        ["batbat_boss"] =           { ["name"] = "batbat",          ["cmd"] = "upgrade", ["type"] = "boss", },
        ["nightsword_type1"] =      { ["name"] = "nightsword",      ["cmd"] = "upgrade", ["type"] = "bloody", },
        ["hammer_gopher"] =         { ["name"] = "hammer",          ["cmd"] = "upgrade", ["type"] = "gopher", },
    }
    local function SpawnItemByCMD(theNPC,_cmd)
        local item = SpawnPrefab(_cmd.name)
        item:PushEvent(_cmd.cmd,_cmd.type)
        item:AddTag("npc_event_deal_with_bat.item")
        local ret = theNPC.components.container:GiveItem(item,1)
        theNPC.npc_base_lib:Change_Item_Skin(item)
        print("npc_event_deal_with_bat item",item,ret)
        return item
    end

    local temp_pro = math.random(1000)/10
    if temp_pro < 10 then
        local item = SpawnItemByCMD(theNPC,item_cmd["batbat_boss"])
        return 5
    elseif temp_pro < 30 then
        local item = SpawnItemByCMD(theNPC,item_cmd["nightsword_type1"])
        return 3
    else
        local item = SpawnItemByCMD(theNPC,item_cmd["hammer_gopher"])            
        return 1
    end

end
-------------------------------------------------------------------------------------------------------------------------------------------------
local function NPC_TASKS_INIT(inst)
    local theNPC = inst.entity:GetParent()
    language_change_say(theNPC)
    Time_Out_Leave(inst)
    theNPC.__item_ask_num = GiveItem(theNPC,true)
    Item_Get_Event_Init(theNPC)
    -- theNPC.npc_base_lib:Equip_Random_Hat()
    -- theNPC.npc_base_lib:Equip_Random_Cloth()
    -- theNPC.npc_base_lib:Equip_Random_Weapon()
    -- theNPC:AddTag("INLIMBO")
    -- theNPC:AddTag("Unable_To_Refuse")
    theNPC.npc_event = inst.prefab
    
    theNPC:AddTag("notarget")
    theNPC:AddTag("noattack")
    theNPC:AddTag("invisible")
end

local function NPC_TASKS(inst)
    local theNPC = inst.entity:GetParent()
    if TheWorld.state.isnight  or TheWorld:HasTag("cave") then
        theNPC.npc_base_lib:Try_2_Set_Light(true)
    else
        theNPC.npc_base_lib:Try_2_Set_Light(false)
    end
    local theplayer = theNPC.__link_player
    if theplayer == nil or theplayer:IsValid() == false then
        inst:Remove()
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")
        print("Warning : theNPC.__link_player == nil")
        return
    end

    if theNPC.event_step == nil then
        if theNPC.npc_everything_data:Add("wait time 000",1) % 10 == 0 then
            Chat_Bubble_Fn(theNPC)
        end
        theNPC.npc_base_lib:Run_Around_Target_In_Range({range = 7,random_range_flag = true , mid_reflash_range = 5})
        
    elseif theNPC.event_step == 1 then

        theNPC.npc_base_lib:Say(theNPC.CHAT_TABLE.it_is_for_you)
        GiveItem(theNPC)

        theNPC.event_step = theNPC.event_step + 1
        theNPC:AddTag("INLIMBO")
    elseif theNPC.event_step == 2 then
        if theNPC.npc_everything_data:Add("wait time 001",1) > 5 then
            theNPC.event_step = theNPC.event_step + 1
        end
        theNPC:AddTag("INLIMBO")
    elseif theNPC.event_step == 3 then
        theNPC:AddTag("INLIMBO")
        inst:Remove()
        theNPC.npc_base_lib:Say("Bye ~ ")
        theNPC:AddDebuff("npc_event_leave","npc_event_leave")

    end
end
--------------------------------------------------------------------------------------------------------------------------------------------------

local function OnAttached(inst,target) -- when the debuff on or player is newSpawn(or through the cave)
    inst.entity:SetParent(target.entity)
    inst.Network:SetClassifiedTarget(target)
    local NPC = inst.entity:GetParent()
    local flag ,error_code= pcall(function(inst,target)
        if TheWorld.ismastersim then

            NPC_TASKS_INIT(inst)


        end
    end,inst,target)
    if flag == false  then
        print("Error : OnAttached(inst,target) ",inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function OnDetached(inst) -- When eliminating from the outside
    local player = inst.entity:GetParent()   
    -- print(" FROM OUSIDE REMOVE ")
    
    -- inst:Remove()
end

local function ExtendDebuff(inst)
    -- inst.countdown = 3 + (inst._level:value() < CONTROL_LEVEL and EXTEND_TICKS or math.floor(TUNING.STALKER_MINDCONTROL_DURATION / FRAMES + .5))
end



local function OnUpdate(inst,ismastersim)
    local NPC = inst.entity:GetParent()
    local flag,error_code = pcall(function(inst,ismastersim)
        -- local NPC = inst.entity:GetParent()

        NPC_TASKS(inst)


    end,inst,ismastersim)
    if flag == false then
        print("Error : OnUpdate(inst,ismastersim) ,step:",NPC.event_step ,inst.prefab)
        print(error_code)
        NPC:Remove()
    end
end

local function fn()
    local inst = CreateEntity()

    inst.entity:AddTransform()
    inst.entity:AddNetwork()

    inst:AddTag("CLASSIFIED")


    -- inst:DoPeriodicTask(1, OnUpdate, nil, TheWorld.ismastersim)  -- in one seconds
    inst:DoPeriodicTask( 0.5, OnUpdate, nil, TheWorld.ismastersim)  -- in 0.5 seconds

    inst.entity:SetPristine()

    if not TheWorld.ismastersim then
        return inst
    end

    inst:AddComponent("debuff")
    inst.components.debuff:SetAttachedFn(OnAttached)
    inst.components.debuff.keepondespawn = false -- 是否保持debuff 到下次登陆
    -- inst.components.debuff:SetDetachedFn(inst.Remove)
    inst.components.debuff:SetDetachedFn(OnDetached)
    -- inst.components.debuff:SetExtendedFn(ExtendDebuff)
    -- ExtendDebuff(inst)


    return inst
end

return Prefab("npc_event_deal_with_bat", fn)
